package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.constants.MessageConstant;
import com.huike.dto.ClueDto;
import com.huike.dto.CluePageQueryDto;
import com.huike.dto.FalseClueDto;
import com.huike.entity.Clue;
import com.huike.entity.ClueTrackRecord;
import com.huike.entity.SysDictData;
import com.huike.entity.SysUser;
import com.huike.mapper.ClueMapper;
import com.huike.mapper.ClueTrackRecordMapper;
import com.huike.mapper.SysDictDataMapper;
import com.huike.mapper.SysUserMapper;
import com.huike.result.PageResult;
import com.huike.result.Result;
import com.huike.service.ClueService;
import com.huike.utils.BaseContext;
import com.huike.utils.ExcelUtil;
import com.huike.vo.ClueVo;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ClueServiceImpl implements ClueService {
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public Result list() {
        LambdaQueryWrapper<Clue> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Clue::getAge, 25);
        List<Clue> tbClues = clueMapper.selectList(lqw);
        return Result.success(tbClues);
    }

    @Override
    public Result getClueList(CluePageQueryDto dto) {
        if (dto == null) {
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        IPage<Clue> pageResult = new Page<>(dto.getPage(), dto.getPageSize());
        LambdaQueryWrapper<Clue> lqw = new LambdaQueryWrapper<>();
        lqw.like(dto.getPhone() != null, Clue::getPhone, dto.getPhone());
        lqw.like(dto.getClueId() != null, Clue::getId, dto.getClueId());
        lqw.eq(dto.getStatus() != null, Clue::getStatus, dto.getStatus());
        lqw.like(dto.getBelonger() != null, Clue::getBelonger, dto.getBelonger());
        lqw.eq(dto.getChannel() != null, Clue::getChannel, dto.getChannel());

        //是否在线索池 0否 1是
        lqw.eq(Clue::getIsPool, 0);
        Date serachTime = dto.getSerachTime();
        if (serachTime!=null){
            Instant instant = serachTime.toInstant();
            // 将 Instant 转换为 LocalDateTime
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            LocalDateTime minDateTime = localDateTime.with(LocalTime.MIN);
            LocalDateTime maxDateTime = localDateTime.with(LocalTime.MAX);
            lqw.le(Clue::getCreateTime, maxDateTime)
                    .ge(Clue::getCreateTime, minDateTime);
        }

        clueMapper.selectPage(pageResult, lqw);
        PageResult result = new PageResult(pageResult.getTotal(), pageResult.getRecords());


        return Result.success(result);
    }

    @Override
    public Result getCluePoolList(CluePageQueryDto dto) {
        if (dto == null) {
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        IPage<Clue> pageResult = new Page<>(dto.getPage(), dto.getPageSize());
        LambdaQueryWrapper<Clue> lqw = new LambdaQueryWrapper<>();
        lqw.like(dto.getPhone() != null, Clue::getPhone, dto.getPhone());
        lqw.like(dto.getClueId() != null, Clue::getId, dto.getClueId());
        lqw.eq(dto.getChannel() != null, Clue::getChannel, dto.getChannel());

        //是否在线索池 0否 1是
        lqw.eq(Clue::getIsPool, 1);
        Date serachTime = dto.getSerachTime();
        if (serachTime!=null){
            Instant instant = serachTime.toInstant();
            // 将 Instant 转换为 LocalDateTime
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            LocalDateTime minDateTime = localDateTime.with(LocalTime.MIN);
            LocalDateTime maxDateTime = localDateTime.with(LocalTime.MAX);
            lqw.le(Clue::getCreateTime, maxDateTime)
                    .ge(Clue::getCreateTime, minDateTime);
        }

        clueMapper.selectPage(pageResult, lqw);
        PageResult result = new PageResult(pageResult.getTotal(), pageResult.getRecords());


        return Result.success(result);

    }

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public Result createClue(ClueDto dto) {
        if (dto == null) {
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        Clue clue = new Clue();
        BeanUtils.copyProperties(dto, clue);
        /*TODO:这个信息就是由前端发送请求,查询字典表,获取的来源渠道id
                通过选择不同id,发起请求,通过来源渠道id,查询出活动id集合和对应的活动名称返回
                前端生成对应的下拉框,选中对应活动则传入活动id到表中存入
         */
        if (dto.getActivityDetail() == null) {
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        clue.setActivityId(Long.valueOf(String.valueOf(dto.getActivityDetail())));

        //字段补充
        clue.setCreateTime(LocalDateTime.now());
        //TODO:创建人
        Long userId = BaseContext.getCurrentId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        //clue.setCreateBy(sysUser.getUserName());
        clue.setCreateBy("admin");
        clue.setUpdateTime(LocalDateTime.now());
        clue.setIsPool(0);
        clueMapper.insert(clue);
        return Result.success();
    }

    /**
     * 批量分配
     * @param
     * @param
     * @return
     */
    @Override
    public Result assign(List<Long> list, String userName) {

        List<Clue> clues = clueMapper.selectBatchIds(list);
        List<Clue> collect = clues.stream().map(clue -> {
            clue.setBelonger(userName);
            return clue;
        }).collect(Collectors.toList());
        //TODO:优化批量添加,userId和belonger关系
        for (Clue clue : collect) {
            clueMapper.updateById(clue);
        }

        return Result.success();
    }

    @Override
    public Result gain(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        List<Clue> clues = clueMapper.selectBatchIds(list);
        //TODO:枚举
        List<Clue> collect = clues.stream().map(clue -> {
            clue.setIsPool(0);
            return clue;
        }).collect(Collectors.toList());
        for (Clue clue : collect) {
            clueMapper.updateById(clue);
        }
        return Result.success();
    }

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public List<SysDictData> findDictData(String dictType) {
        LambdaQueryWrapper<SysDictData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDictData::getDictType,dictType);
        List<SysDictData> sysDictData = sysDictDataMapper.selectList(lqw);
        return sysDictData;
    }

    /**
     * 伪线索上报
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result submitFalseClue(FalseClueDto dto) {
        if (dto==null){
            return Result.error(MessageConstant.DATA_NOT_EXIST);

        }
        Long clueId = dto.getClueId();
        if (clueId ==null){
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        Clue clue = clueMapper.selectById(clueId);
        clue.setBelonger("无");
        clue.setFalseReason(dto.getFalseReason());
        clue.setFalseRemark(dto.getFalseRemark());
        clue.setIsPool(1);
        clue.setFalseCount(clue.getFalseCount()+1);
        clueMapper.updateById(clue);
        return Result.success();
    }

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    /**
     * 查询线索跟进记录
     * @param clueId
     * @return
     */
    @Override
    public Result findByClueId(Long clueId) {
        if (clueId==null){
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<ClueTrackRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ClueTrackRecord::getClueId,clueId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(lqw);
        return Result.success(clueTrackRecords);
    }

    @Override
    public List<Clue> upExcel(MultipartFile file) {
        List<Clue> clues = new ArrayList<>();
        try {
            List<String[]> list = ExcelUtil.readExcel(file);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Clue clue = new Clue();
                    //字段补充
                    clue.setCreateTime(LocalDateTime.now());
                    //TODO:创建人
                    Long userId = BaseContext.getCurrentId();
                    SysUser sysUser = sysUserMapper.selectById(userId);
                    //clue.setCreateBy(sysUser.getUserName());
                    clue.setCreateBy("admin");
                    clue.setUpdateTime(LocalDateTime.now());
                    clue.setIsPool(0);
                    if (list.get(i)[0] != null && list.get(i)[0] != "") {
                        for (int j = 0; j < list.get(i).length; j++) {
                            switch (j) {
                                case 0: {
                                    //手机号
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                       clue.setPhone(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 1: {
                                    //渠道来源
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {

                                       if ("线上活动".equals(list.get(i)[j])){
                                           clue.setChannel("1");
                                       }
                                       if ("推广介绍".equals((list.get(i)[j]))){
                                           clue.setChannel("2");
                                       }
                                    }
                                    break;
                                }
                                case 2: {
                                    //活动信息
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setActivityName(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 3: {
                                    //姓名
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setName(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 4: {
                                    //性别
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setSex(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 5: {
                                    //年龄
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setAge(Integer.valueOf(list.get(i)[j]));
                                    }
                                    break;
                                }
                                case 6: {
                                    //微信
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setWeixin(list.get(i)[j]);
                                    }
                                    break;
                                }
                                case 7: {
                                    //qq
                                    if (list.get(i)[j] != null && !list.get(i)[j].equals("")) {
                                        clue.setQq(list.get(i)[j]);
                                    }
                                    break;
                                }
                                default: {
                                    break;
                                }
                            }
                        }
                    }
                    clues.add(clue);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        batchInsertClue(clues);
        return null;
    }

    @Override
    public Result createClueRecord(ClueTrackRecord clueTrackRecord) {
        if (clueTrackRecord.getClueId()==null){
            return Result.error(MessageConstant.ClUE_NOT_ID);
        }
        clueTrackRecordMapper.insert(clueTrackRecord);
        return Result.success();
    }

    @Override
    public Result getById(Long clueId) {
        if (clueId==null){
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        Clue clue = clueMapper.selectById(clueId);
        if (clue==null){
            return Result.error(MessageConstant.DATA_NOT_EXIST);
        }
        ClueVo clueVo = new ClueVo();
        BeanUtils.copyProperties(clue,clueVo);
        clueVo.setCreateTime(clue.getCreateTime());
        clueVo.setAttributionTime(clue.getCreateTime());
        clueVo.setActivityDetail(clue.getActivityName());
        return Result.success(clueVo);
    }

    @Override
    public void changeBusiness(Long clueId) {

    }


    /**
     * 批量添加线索的方法
     * @param clues
     */
    private void batchInsertClue(List<Clue> clues) {
        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();
       // String userName = sysUserMapper.selectById(userId).getUserName();
        for (Clue clue : clues) {
            //字段补充
            clue.setCreateTime(now);
           // clue.setCreateBy(userName);
            clue.setCreateBy("admin");
            clue.setUpdateTime(now);
            clue.setIsPool(0);
            clueMapper.insert(clue);
        }
    }
}
